package cn.wch.ch34xuartdemo.adapter;

import android.hardware.usb.UsbDevice;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import cn.wch.ch34xuartdemo.utils.FormatUtil;
import cn.wch.uartlib.WCHUARTManager;
import cn.wch.ch34xuartdemo.LogUtil;
import cn.wch.ch34xuartdemo.R;
import cn.wch.ch34xuartdemo.entity.DeviceEntity;
import cn.wch.ch34xuartdemo.entity.ModemEntity;
import cn.wch.ch34xuartdemo.entity.ModemErrorEntity;
import cn.wch.ch34xuartdemo.entity.SerialEntity;

public class DeviceAdapter extends RecyclerView.Adapter<DeviceAdapter.MyViewHolder> {

    private static final String TAG = "DeviceAdapter";
    private ArrayList<DeviceEntity> deviceList;
    private HashMap<DeviceEntity,SerialListAdapter> maps;
    private FragmentActivity activity;
    private OnActionListener onActionListener;

    private final int ITEM_TYPE_EMPTY = 3;
    private final int ITEM_TYPE_NORMAL = 4;
    private View mEmptyView=null;

    public DeviceAdapter(@NonNull FragmentActivity activity) {
        this.activity=activity;
        deviceList=new ArrayList<>();
        maps=new HashMap<>();
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        switch (viewType){
            case ITEM_TYPE_EMPTY:
                return new MyViewHolder(mEmptyView);
            case ITEM_TYPE_NORMAL:
                return new MyViewHolder(LayoutInflater.from(activity).inflate(R.layout.device_item,parent,false));
        }
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        int type=getItemViewType(position);
        if(type == ITEM_TYPE_EMPTY)
            return;

        DeviceEntity entity = deviceList.get(position);
        //绘制
        holder.description.setText(String.format(Locale.getDefault(),"%s(%s)",entity.getUsbDevice().getDeviceName(),entity.getDescription()));

        Log.d(TAG,"description "+String.format(Locale.getDefault(),"%s(%s)",entity.getUsbDevice().getDeviceName(),entity.getDescription()));

        holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeDevice(entity.getUsbDevice(),entity);
            }
        });
        //初始化recyclerview
        RecyclerView recyclerView = holder.recyclerView;
        ArrayList<SerialEntity> serialEntities = entity.getSerialEntities();
        Log.d(TAG,"serialEntities  大小:"+serialEntities.size());

        //first_blue   first_yellow  first_white
        holder.first_blue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083000002AA0901027A");
            }
        });
        holder.first_yellow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083000002AA0902027A");

            }
        });
        holder.first_white.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083000002AA0903027A");

            }
        });


        //lightbelt_liushui   lightbelt_danse  lightbelt_jianbian

        holder.lightbelt_liushui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083000002AA0A01027A");

            }
        });

        holder.lightbelt_danse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083000002AA0A02027A");

            }
        });

        holder.lightbelt_jianbian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083000002AA0A03027A");

            }
        });

        //    lightbelt_red  lightbelt_green  lightbelt_blue

        holder.lightbelt_red.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083132601000000007A");

            }
        });

        holder.lightbelt_green.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083132601000100007A");

            }
        });

        holder.lightbelt_blue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083132601000200007A");

            }
        });

        holder.second_one.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083000002AA0801027A");

            }
        });

        holder.second_two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083000002AA0802027A");

            }
        });
        holder.third_one.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083000002AA0803027A");

            }
        });
        holder.third_two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083000002AA0804027A");

            }
        });
        holder.fourth_one.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083000002AA0805027A");

            }
        });
        holder.fourth_two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083000002AA0806027A");

            }
        });
        // //  //lightbelt_yellow   lightbelt_qin  lightbelt_zise  lightbelt_white


        holder.lightbelt_yellow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083132601000300007A");

            }
        });
        holder.lightbelt_qin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083132601000400007A");

            }
        });
        holder.lightbelt_zise.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083132601000500007A");

            }
        });

        holder.lightbelt_white.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeData(entity.getSerialEntities().get(0),"AA0000080000041083132601000600007A");

            }
        });



        /*
        second_one=itemView.findViewById(R.id.second_one);
            second_two=itemView.findViewById(R.id.second_two);
            third_one=itemView.findViewById(R.id.third_one);
            third_two=itemView.findViewById(R.id.third_two);
            fourth_one=itemView.findViewById(R.id.fourth_one);
            fourth_two=itemView.findViewById(R.id.fourth_two);
         */




      /*  SerialListAdapter serialListAdapter=new SerialListAdapter(activity,serialEntities);
        maps.put(entity, serialListAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(activity,LinearLayoutManager.VERTICAL,false));
        recyclerView.setAdapter(serialListAdapter);
        recyclerView.setNestedScrollingEnabled(false);*/
    }

    @Override
    public int getItemCount() {
        int itemCount=deviceList.size();
        if (null != mEmptyView && itemCount == 0) itemCount++;
        return itemCount;
    }

    @Override
    public int getItemViewType(int position) {
        if (null != mEmptyView && deviceList.size() == 0)
            return ITEM_TYPE_EMPTY;
        return ITEM_TYPE_NORMAL;
    }

    public boolean hasExist(@NonNull DeviceEntity deviceEntity){
        for (DeviceEntity entity : deviceList) {
            if(entity.getUsbDevice().equals(deviceEntity.getUsbDevice())){
                //已经存在
                 Log.d(TAG,"已经存在");
                return true;
            }
        }
        return false;
    }

    public void addDevice(@NonNull DeviceEntity deviceEntity){
        if(!hasExist(deviceEntity)){
            deviceList.add(deviceEntity);
            notifyItemInserted(deviceList.size());
        }
    }

    public void removeDevice(@NonNull DeviceEntity deviceEntity){
        int index=-1;
        for (int i = 0; i < deviceList.size(); i++) {
            DeviceEntity entity = deviceList.get(i);
            if(entity.getUsbDevice().equals(deviceEntity.getUsbDevice())){
                index=i;
            }
        }
        if(index>=0){
            maps.remove(deviceEntity);
            deviceList.remove(index);
            notifyItemRemoved(index);
        }
    }

    public void removeDevice(@NonNull UsbDevice usbDevice){

        int index=-1;
        for (int i = 0; i < deviceList.size(); i++) {
            DeviceEntity entity = deviceList.get(i);
            if(entity.getUsbDevice().equals(usbDevice)){
                index=i;
                break;
            }
        }
        if(index>=0){
            maps.remove(deviceList.get(index));
            deviceList.remove(index);
            notifyItemRemoved(index);
        }
        if(onActionListener!=null){
            onActionListener.onRemove(usbDevice);
        }
        WCHUARTManager.getInstance().disconnect(usbDevice);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position, @NonNull List<Object> payloads) {

        if(payloads.isEmpty()){
            onBindViewHolder(holder,position);
        }else {
            DeviceEntity deviceEntity = deviceList.get(position);
            SerialListAdapter serialListAdapter = maps.get(deviceEntity);
            if(serialListAdapter==null){
                return;
            }
            Object o = payloads.get(0);
            if(o instanceof ModemEntity){
                serialListAdapter.updateModemStatus((ModemEntity) o);
            }else if( o instanceof ModemErrorEntity){
                serialListAdapter.updateModemErrorStatus((ModemErrorEntity) o);
            }
        }

    }

    public void updateDeviceModemStatus(@NonNull UsbDevice usbDevice, int serialNumber, boolean DCD, boolean DSR, boolean CTS, boolean RING){
        int index=-1;
        for (int i = 0; i < deviceList.size(); i++) {
            DeviceEntity entity = deviceList.get(i);
            if(entity.getUsbDevice().equals(usbDevice)){
                index=i;
            }
        }
        if(index>=0){
            notifyItemChanged(index,new ModemEntity(serialNumber, DCD, DSR, CTS, RING));
        }
    }

    public void updateDeviceModemErrorStatus(@NonNull UsbDevice usbDevice,@NonNull ModemErrorEntity error){
        int index=-1;
        for (int i = 0; i < deviceList.size(); i++) {
            DeviceEntity entity = deviceList.get(i);
            if(entity.getUsbDevice().equals(usbDevice)){
                index=i;
            }
        }
        if(index>=0){
            notifyItemChanged(index,error);
        }
    }

    public class MyViewHolder extends RecyclerView.ViewHolder{
        TextView description;
        TextView first_blue;
        TextView first_yellow;
        TextView first_white;

        //lightbelt_liushui   lightbelt_danse  lightbelt_jianbian
        //    lightbelt_red  lightbelt_green  lightbelt_blue
        TextView lightbelt_liushui;
        TextView lightbelt_danse;
        TextView lightbelt_jianbian;
        TextView lightbelt_red;
        TextView lightbelt_green;
        TextView lightbelt_blue;

        // second_one second_two  third_one third_two  fourth_one  fourth_two
        TextView second_one;
        TextView second_two;
        TextView third_one;
        TextView third_two;
        TextView fourth_one;
        TextView fourth_two;


        TextView lightbelt_yellow;
        TextView lightbelt_qin;
        TextView lightbelt_zise;
        TextView lightbelt_white;


        Button button;
        RecyclerView recyclerView;


        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            if(itemView==mEmptyView){
                return;
            }
            description=itemView.findViewById(R.id.tvDescription);
            button=itemView.findViewById(R.id.btnClose);
            recyclerView=itemView.findViewById(R.id.rvSerial);


            first_blue=itemView.findViewById(R.id.first_blue);
            first_yellow=itemView.findViewById(R.id.first_yellow);
            first_white=itemView.findViewById(R.id.first_white);

            /*
             //lightbelt_liushui   lightbelt_danse  lightbelt_jianbian
        //    lightbelt_red  lightbelt_green  lightbelt_blue

             */
            lightbelt_liushui=itemView.findViewById(R.id.lightbelt_liushui);
            lightbelt_danse=itemView.findViewById(R.id.lightbelt_danse);
            lightbelt_jianbian=itemView.findViewById(R.id.lightbelt_jianbian);
            lightbelt_red=itemView.findViewById(R.id.lightbelt_red);
            lightbelt_green=itemView.findViewById(R.id.lightbelt_green);
            lightbelt_blue=itemView.findViewById(R.id.lightbelt_blue);

            //  // second_one second_two  third_one third_two  fourth_one  fourth_two
            second_one=itemView.findViewById(R.id.second_one);
            second_two=itemView.findViewById(R.id.second_two);
            third_one=itemView.findViewById(R.id.third_one);
            third_two=itemView.findViewById(R.id.third_two);
            fourth_one=itemView.findViewById(R.id.fourth_one);
            fourth_two=itemView.findViewById(R.id.fourth_two);


            lightbelt_yellow=itemView.findViewById(R.id.lightbelt_yellow);
            lightbelt_qin=itemView.findViewById(R.id.lightbelt_qin);
            lightbelt_zise=itemView.findViewById(R.id.lightbelt_zise);
            lightbelt_white=itemView.findViewById(R.id.lightbelt_white);


        }
    }

    public void setEmptyView(View view){
        mEmptyView=view;
    }

    public interface OnActionListener{
        void onRemove(UsbDevice usbDevice);
    }

    public void setActionListener(OnActionListener actionListener){
        this.onActionListener=onActionListener;
    }

    //关闭设备
    private void closeDevice(@NonNull UsbDevice usbDevice, DeviceEntity entity){
        WCHUARTManager.getInstance().disconnect(usbDevice);
        removeDevice(entity);
        if(onActionListener!=null){
            onActionListener.onRemove(usbDevice);
        }
    }

    public void writeData(SerialEntity serialEntity, String cmd){
        String s =cmd;// holder.writeBuffer.getText().toString();
        Log.d(TAG," write  s:"+s);
        if(TextUtils.isEmpty(s)){
            Log.d(TAG,"发送内容为空");
            return;
        }//00 00 04 10 83 00 00 02 AA 08 02 02  //00000 0000041083000002AA080202
        byte[] bytes = null;
       // if(holder.scWrite.isChecked()){
            if(!s.matches("([0-9|a-f|A-F]{2})*")){
                Log.d(TAG,"发送内容不符合HEX规范");
                return;
            }
            bytes= FormatUtil.hexStringToBytes(s);
        /*}else {
            bytes = s.getBytes(StandardCharsets.UTF_8);
        }*/
        int ret = writeData(serialEntity.getUsbDevice(), serialEntity.getSerialNumber(), bytes, bytes.length);
        if(ret>0){
            //更新发送计数
           /* int writeCount = getWriteCount(serialEntity.getSerialNumber());
            writeCount+=ret;
            setWriteCount(serialEntity.getSerialNumber(),writeCount);
            holder.writeCount.setText(String.format(Locale.getDefault(),"发送计数：%d字节",writeCount));*/
            Log.d(TAG,"发送成功");
        }else {
            Log.d(TAG,"发送失败");
        }

    }


    //写数据
    int writeData(UsbDevice usbDevice,int serialNumber,@NonNull byte[] data,int length){
        try {
            int write = WCHUARTManager.getInstance().writeData(usbDevice, serialNumber, data, length,2000);
            return write;
        } catch (Exception e) {
            Log.d(TAG,"  writeData 写入数据失败...");
            Log.d(TAG,e.getMessage());

        }
        return -2;
    }

}
